<template>
  <div class="merchant-detail-container">
    <!-- 头部 -->
    <Header />
    
    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 商家信息区域 -->
      <div class="merchant-info-wrapper">
        <div class="merchant-info-card" v-if="merchant">
          <div class="merchant-header">
            <div class="merchant-logo">
              <img :src="merchant.shopLogo || 'https://via.placeholder.com/80'" :alt="merchant.name">
            </div>
            <div class="merchant-basic-info">
              <h1 class="merchant-name">{{ merchant.shopName }}</h1>
              <div class="merchant-rating">
                <el-rate v-model="merchant.rating" disabled text-color="#ff9900"></el-rate>
                <span class="rating-value">{{ merchant.rating }}分</span>
                <span class="monthly-sales">月售 {{ merchant.monthlySales }} 单</span>
              </div>
              <div class="merchant-status">
                <span class="status-tag" :class="{ 'open': merchant.businessStatus === 1 }">
                  {{ merchant.businessStatus === 1 ? '营业中' : '休息中' }}
                </span>
                <span class="delivery-time">约{{ merchant.deliveryTime || 30 }}分钟送达</span>
              </div>
              <div class="merchant-notice" v-if="merchant.notice">
                <span class="notice-title">公告：</span>
                <span class="notice-content">{{ merchant.notice }}</span>
              </div>
            </div>
          </div>
          <div class="merchant-description">
            {{ merchant.description }}
          </div>
        </div>
      </div>
      
      <!-- 菜品分类和列表 -->
      <div class="food-section-wrapper">
        <div class="food-section" v-if="!loading">
          <!-- 左侧分类导航 -->
          <div class="category-nav">
            <ul class="category-list">
              <li 
                v-for="(category, index) in categories" 
                :key="index" 
                :class="{ 'active': activeCategory === category }"
                @click="switchCategory(category)">
                {{ category }}
              </li>
            </ul>
          </div>
          
          <!-- 右侧菜品列表 -->
          <div class="food-list-container">
            <div class="category-title" v-if="activeCategory">{{ activeCategory }}</div>
            
            <!-- 菜品列表 -->
            <div class="food-list" v-if="foodList.length > 0">
              <div class="food-item" v-for="food in foodList" :key="food.id">
                <div class="food-image">
                  <img :src="food.image || 'https://via.placeholder.com/120'" :alt="food.name">
                </div>
                <div class="food-content">
                  <div class="food-name">{{ food.name }}</div>
                  <div class="food-desc">{{ food.description }}</div>
                  <div class="food-sales">月售 {{ food.sales || 0 }} 份</div>
                  <div class="food-price-actions">
                    <div class="food-price">¥{{ food.price }}</div>
                    <div class="food-actions">
                      <el-button type="primary" size="small" circle icon="el-icon-plus" @click="addToCart(food)"></el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 无数据提示 -->
            <div class="no-data" v-else>
              <i class="el-icon-dish"></i>
              <p>该分类暂无菜品</p>
            </div>
          </div>
        </div>
        
        <!-- 加载中 -->
        <div class="loading-container" v-else>
          <el-skeleton :rows="10" animated />
        </div>
      </div>
    </div>
    
    <!-- 底部 -->
    <Footer />
    
    <!-- 购物车悬浮按钮 -->
    <div class="cart-fab" v-if="cartItemCount > 0" @click="viewCart">
      <el-badge :value="cartItemCount" :max="99">
        <i class="el-icon-shopping-cart-2"></i>
      </el-badge>
    </div>
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { getMerchantById } from '@/api/merchant'
import { getFoodsByMerchant, getFoodsByCategory, getMerchantFoodCategories } from '@/api/food'
import { mapGetters } from 'vuex'
import { addToCart } from '@/api/cart'

export default {
  name: 'MerchantDetail',
  components: {
    Header,
    Footer
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      // 商家信息
      merchant: null,
      // 菜品分类
      categories: ['全部'],
      // 当前选中的分类
      activeCategory: '全部',
      // 菜品列表
      foodList: [],
      // 加载状态
      loading: true
    }
  },
  computed: {
    ...mapGetters(['cartItemCount', 'cartItemsByMerchant']),
    // 当前商家的购物车商品数量
    currentMerchantCartCount() {
      const items = this.cartItemsByMerchant(Number(this.id))
      return items.length
    }
  },
  created() {
    // 获取商家信息
    this.fetchMerchantInfo()
    // 获取菜品分类
    this.fetchFoodCategories()
    // 获取菜品列表
    this.fetchFoodList()
  },
  methods: {
    // 获取商家信息
    fetchMerchantInfo() {
      getMerchantById(this.id).then(response => {
        if (response.code == 200) {
          this.merchant = response.data
        } else {
          this.$message.error(response.message || '获取商家信息失败')
        }
      }).catch(error => {
        console.error('获取商家信息失败', error)
        this.$message.error('获取商家信息失败，请稍后再试')
      })
    },
    // 获取菜品分类
    fetchFoodCategories() {
      getMerchantFoodCategories(this.id).then(response => {
        if (response.code == 200) {
          // 添加"全部"分类
          const categories = ['全部', ...response.data]
          this.categories = categories
        } else {
          this.$message.error(response.message || '获取菜品分类失败')
        }
      }).catch(error => {
        console.error('获取菜品分类失败', error)
        this.$message.error('获取菜品分类失败，请稍后再试')
      })
    },
    // 获取菜品列表
    fetchFoodList() {
      this.loading = true
      
      // 根据分类获取菜品
      const fetchPromise = this.activeCategory === '全部' 
        ? getFoodsByMerchant(this.id, { status: 1 }) // 状态1表示上架中的菜品
        : getFoodsByCategory(this.activeCategory, Number(this.id))
      
      fetchPromise.then(response => {
        if (response.code == 200) {
          this.foodList = response.data || []
        } else {
          this.$message.error(response.message || '获取菜品列表失败')
        }
      }).catch(error => {
        console.error('获取菜品列表失败', error)
        this.$message.error('获取菜品列表失败，请稍后再试')
      }).finally(() => {
        this.loading = false
      })
    },
    // 切换菜品分类
    switchCategory(category) {
      this.activeCategory = category
      this.fetchFoodList()
    },
    // 添加到购物车
    addToCart(food) {
      // 检查用户是否登录
      if (!this.$store.getters.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push({
          path: '/login',
          query: { redirect: this.$route.fullPath }
        })
       
      }
      
      // 检查商家是否休息中
      if (this.merchant && this.merchant.businessStatus === 0) {
        this.$message.warning('该商家休息中，暂不接单')
        return
      }
      
      // 构建购物车项
      const cartItem = {
        foodId: food.id,
        userId: this.$store.getters.currentUser.id,
        merchantId: Number(this.id),
        merchantName: this.merchant ? this.merchant.name : '',
        quantity: 1,
        remark: ''
      }
      
      // 调用后端API添加到购物车
      addToCart(cartItem).then(response => {
        if (response.code == 200) {
          // 添加成功后更新本地购物车状态
          this.$store.dispatch('getCartList')
          this.$message.success(`已将 ${food.name} 加入购物车`)
          this.$store.commit('ADD_TO_CART', cartItem)
          return
        } else {
          this.$message.error(response.message || '添加到购物车失败')
        }
      }).catch(error => {
        console.error('添加到购物车失败', error)
        this.$message.error('添加到购物车失败，请稍后再试')
      })
    },
    // 查看购物车
    viewCart() {
      this.$router.push('/cart')
    }
  }
}
</script>

<style scoped>
.merchant-detail-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding-bottom: 30px;
}

.merchant-info-wrapper {
  padding: 20px;
  background-color: #fff;
  margin-bottom: 20px;
}

.merchant-info-card {
  max-width: 1200px;
  margin: 0 auto;
}

.merchant-header {
  display: flex;
  margin-bottom: 15px;
}

.merchant-logo {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 20px;
}

.merchant-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.merchant-basic-info {
  flex: 1;
}

.merchant-name {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.merchant-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.rating-value {
  margin-left: 5px;
  margin-right: 15px;
  color: #ff9900;
}

.monthly-sales {
  color: #666;
}

.merchant-status {
  margin-bottom: 10px;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #f5f5f5;
  color: #666;
  margin-right: 15px;
}

.status-tag.open {
  background-color: #e1f3d8;
  color: #67c23a;
}

.delivery-time {
  color: #666;
}

.merchant-notice {
  color: #666;
}

.notice-title {
  font-weight: bold;
}

.merchant-description {
  color: #666;
  line-height: 1.6;
}

.food-section-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.food-section {
  display: flex;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.category-nav {
  width: 200px;
  background-color: #f8f8f8;
  border-right: 1px solid #eee;
}

.category-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.category-list li {
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: all 0.3s;
}

.category-list li:hover {
  background-color: #f0f0f0;
}

.category-list li.active {
  background-color: #fff;
  color: #409EFF;
  font-weight: bold;
  border-left: 3px solid #409EFF;
}

.food-list-container {
  flex: 1;
  padding: 20px;
}

.category-title {
  font-size: 18px;
  font-weight: bold;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.food-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.food-item {
  display: flex;
  padding: 15px;
  border-radius: 4px;
  transition: all 0.3s;
  border: 1px solid #eee;
}

.food-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.food-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
}

.food-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.food-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.food-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.food-sales {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.food-price-actions {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 10px;
}

.loading-container {
  padding: 20px;
}

.cart-fab {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #409EFF;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  cursor: pointer;
  z-index: 99;
}

.cart-fab i {
  font-size: 24px;
}
</style> 